﻿package net.wangit.view.util;

import java.util.HashMap;
import java.util.Map;

import net.wangit.util.FileUtil;
import net.wangit.util.StringUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class FileCache {

	private static final Log log = LogFactory.getLog(FileCache.class);
	private static final String CACHE = "cache";
	private static Map<String, String> files = new HashMap<String, String>();

	private FileCache() {
	}

	public static synchronized String get(String path) {
		String content = files.get(path);
		if (content != null)
			return content;
		content = FileUtil.read(path);
		boolean cache = cache(content);
		if (cache) {
			files.put(path, content);
			if (log.isDebugEnabled())
				log.debug((new StringBuilder("file '")).append(path)
						.append("' has been cached.").toString());
		}
		return content;
	}

	private static boolean cache(String content) {
		String temp = StringUtil.find(content, "<!--", "-->");
		return temp != null && temp.trim().equals(FileCache.CACHE);
	}

}
